/**
 * Copyright (C) 2009, 2010 SC 4ViewSoft SRL
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cc.mango.android.chart;

import java.util.ArrayList;
import java.util.List;

import org.achartengine.chart.AbstractChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.chart.ScatterChart;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation;
import org.achartengine.util.MathHelper;

import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.activity.chart.NvChart;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.view.MotionEvent;
import static cc.mango.android.chartutil.ChartCommons.*;

/**
 * The XY chart rendering class.
 */
public class RsiChart extends DownXYChart
{

	/**
	 * Builds a new XY chart instance.
	 * 
	 * @param dataset the multiple series dataset
	 * @param renderer the multiple series renderer
	 */
	public RsiChart(XYMultipleSeriesDataset dataset,
			XYMultipleSeriesRenderer renderer)
	{
		super(dataset, renderer);
		mDataset = dataset;
		mRenderer = renderer;
	}

	/**
	 * The graphical representation of the XY chart.
	 * 
	 * @param canvas the canvas to paint to
	 * @param x the top left x value of the view to draw to
	 * @param y the top left y value of the view to draw to
	 * @param width the width of the view to draw to
	 * @param height the height of the view to draw to
	 */
	@Override
	public void draw(Canvas canvas, int x, int y, int width, int height)
	{
		Paint paint = new Paint();
		paint.setAntiAlias(mRenderer.isAntialiasing());

		initSize(width, height);

		int left = x + leftWidth;
		int top = y + topHeight;
		int right = x + width - rightWidth;
		int bottom = y + height - bottomHeight;
		if (screenR == null)
		{
			screenR = new Rect();
		}
		screenR.set(left, top, right, bottom);

		//    drawBackground(mRenderer, canvas, x, y, width, height, paint);
		///by zha//////////////
		drawBackground(mRenderer, canvas, left, top, right - left, bottom
				- top, paint);
		//by zhengan////////////

		drawBackgroundLine(canvas, left, top, right - left, bottom - top,
				new Paint());//背景红线

		if (paint.getTypeface() == null
				|| !paint.getTypeface().toString().equals(
						mRenderer.getTextTypefaceName())
				|| paint.getTypeface().getStyle() != mRenderer
						.getTextTypefaceStyle())
		{
			paint.setTypeface(Typeface.create(mRenderer
					.getTextTypefaceName(), mRenderer
					.getTextTypefaceStyle()));
		}
		Orientation or = mRenderer.getOrientation();

		double minX = mRenderer.getXAxisMin();
		double maxX = mRenderer.getXAxisMax();
		double minY = mRenderer.getYAxisMin();
		double maxY = mRenderer.getYAxisMax();
		boolean isMinXSet = mRenderer.isMinXSet();
		boolean isMaxXSet = mRenderer.isMaxXSet();
		boolean isMinYSet = mRenderer.isMinYSet();
		boolean isMaxYSet = mRenderer.isMaxYSet();

		int sLength = mDataset.getSeriesCount();
		String[] titles = new String[sLength];
		for (int i = 0; i < sLength; i++)
		{
			XYSeries series = mDataset.getSeriesAt(i);
			titles[i] = series.getTitle();
			if (series.getItemCount() == 0)
			{
				continue;
			}
			if (!isMinXSet)
			{
				double minimumX = series.getMinX();
				minX = Math.min(minX, minimumX);
				calcRange[0] = minX;
			}
			if (!isMaxXSet)
			{
				double maximumX = series.getMaxX();
				maxX = Math.max(maxX, maximumX);
				calcRange[1] = maxX;
			}
			if (!isMinYSet)
			{
				double minimumY = series.getMinY();
				minY = Math.min(minY, (float) minimumY);
				calcRange[2] = minY;
			}
			if (!isMaxYSet)
			{
				double maximumY = series.getMaxY();
				maxY = Math.max(maxY, (float) maximumY);
				calcRange[3] = maxY;
			}
		}
		if (maxX - minX != 0)
		{
			//      xPixelsPerUnit = (right - left) / (maxX - minX);
			int count = this.mDataset.getSeriesAt(0).getItemCount();
			if (count == 0)
			{
				return;
			}
			xPixelsPerUnit = 1.0f * (right - left) / (count - 1);
		}
		if (maxY - minY != 0)
		{
			yPixelsPerUnit = (float) ((bottom - top) / (maxY - minY));

			//    	yPixelsPerUnit = 1 ((bottom - top) / (maxY - minY));
		}

		boolean hasValues = false;
		for (int i = 0; i < sLength; i++)
		{
			XYSeries series = mDataset.getSeriesAt(i);
			if (series.getItemCount() == 0)
			{
				continue;
			}
			hasValues = true;
			SimpleSeriesRenderer seriesRenderer = mRenderer
					.getSeriesRendererAt(i);
			int originalValuesLength = series.getItemCount();
			float[] points = null;
			int valuesLength = originalValuesLength;
			int length = valuesLength * 2;

			/////////////////////////////
			//去掉前一段为0的区域        	
			TDStockLog.d("Print_Info", "length:" + length);

			int k = 0;

			while (k < originalValuesLength
					&& isEqual(series.getY(k), RSI_DEFAUTE_VALUE))
			{

				k += 1;
			}
			TDStockLog.d("Print_Info", "k:" + k);
			length = length - k * 2;
			TDStockLog.d("Print_Info", "length:" + length);

			if (length < 2)
			{
				continue;
			}

			points = new float[length];
			for (int j = 0; j < length; j += 2)
			{
				int index = j / 2 + k;
				//        points[j] = (float) (left + xPixelsPerUnit * (series.getX(index) - minX));
				points[j] = (float) (left + xPixelsPerUnit * index);
				points[j + 1] = (float) (bottom - yPixelsPerUnit
						* (series.getY(index) - minY));
			}
			/////////////////////////////////

			drawSeries(canvas, paint, points, seriesRenderer, Math.min(
					bottom, (float) (bottom + yPixelsPerUnit * minY)), i);
			if (isRenderPoints(seriesRenderer))
			{
				ScatterChart pointsChart = new ScatterChart(mDataset,
						mRenderer);
				pointsChart.drawSeries(canvas, paint, points,
						seriesRenderer, 0, i);
			}
			paint.setTextSize(mRenderer.getChartValuesTextSize());
			if (or == Orientation.HORIZONTAL)
			{
				paint.setTextAlign(Align.CENTER);
			}
			else
			{
				paint.setTextAlign(Align.LEFT);
			}
			if (mRenderer.isDisplayChartValues())
			{
				drawChartValuesText(canvas, series, paint, points, i);
			}
		}

		boolean showLabels = mRenderer.isShowLabels() && hasValues;

		if (showLabels)
		{
			paint.setColor(mRenderer.getLabelsColor());
			paint.setTextSize(mRenderer.getLabelsTextSize());
			paint.setTextAlign(Align.CENTER);

			//draw y labels
			drawYLabels(canvas, paint);

		}

		if (getIsTouching())
		{
			drawVerticalLine(canvas, getXLocation(getIndex()), top, bottom);

		}

	}

	/**
	 * Returns if the chart should display the points as a certain shape.
	 * 
	 * @param renderer the series renderer
	 */
	public boolean isRenderPoints(SimpleSeriesRenderer renderer)
	{
		return ((XYSeriesRenderer) renderer).getPointStyle() != PointStyle.POINT;
	}

	public void drawBackgroundLine(Canvas canvas, int x, int y, int width,
			int height, Paint paint)
	{

		paint.setColor(Color.RED);
		paint.setAlpha(180);
		paint.setStyle(Style.FILL);
		paint.setStrokeWidth(0.5f);
		int lineCount = 2;//vertical number

		float startY = y;

		float stopX = x + width;

		float step = 1.0f * height / (lineCount + 1);

		for (int i = 1; i <= lineCount; i++)
		{
			startY = y + step * i;

			canvas.drawLine(x, startY, stopX, startY, paint);

		}

	}

	/**
	 * The graphical representation of a series.
	 * 
	 * @param canvas the canvas to paint to
	 * @param paint the paint to be used for drawing
	 * @param points the array of points to be used for drawing the series
	 * @param seriesRenderer the series renderer
	 * @param yAxisValue the minimum value of the y axis
	 * @param seriesIndex the index of the series currently being drawn
	 */
	public void drawSeries(Canvas canvas, Paint paint, float[] points,
			SimpleSeriesRenderer seriesRenderer, float yAxisValue,
			int seriesIndex)
	{
		int length = points.length;
		XYSeriesRenderer renderer = (XYSeriesRenderer) seriesRenderer;
		float lineWidth = paint.getStrokeWidth();
		paint.setStrokeWidth(renderer.getLineWidth());
		if (renderer.isFillBelowLine())
		{
			paint.setColor(renderer.getFillBelowLineColor());
			int pLength = points.length;
			float[] fillPoints = new float[pLength + 4];
			System.arraycopy(points, 0, fillPoints, 0, length);
			fillPoints[0] = points[0] + 1;
			fillPoints[length] = fillPoints[length - 2];
			fillPoints[length + 1] = yAxisValue;
			fillPoints[length + 2] = fillPoints[0];
			fillPoints[length + 3] = fillPoints[length + 1];
			paint.setStyle(Style.FILL);
			drawPath(canvas, fillPoints, paint, true);
		}
		paint.setColor(seriesRenderer.getColor());
		paint.setStyle(Style.STROKE);
		drawPath(canvas, points, paint, false);
		paint.setStrokeWidth(lineWidth);
	}

	public List<String> getYLabels(double start, double end, int numLabels)
	{

		if (yLabels != null)
		{

			return yLabels;
		}

		yLabels = new ArrayList<String>();

		yLabels.add(0 + "");
		yLabels.add(30 + "");
		yLabels.add(70 + "");
		yLabels.add(100 + "");

		return yLabels;
	}

}
